package com.quan.commons.interceptor;

import com.alibaba.fastjson.JSON;
import com.quan.commons.constant.CommonsConstant;
import com.quan.commons.properties.SysProperties;
import com.quan.commons.utils.JwtUtils;
import com.quan.commons.utils.RedisUtils;
import com.quan.commons.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;

/**
 * Token验证拦截器
 *
 * @author yhaoquan
 */
@Slf4j
@Component
public class WebSecurityAuthTokenInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private SysProperties sysProperties;

    /**
     * 这个方法是在访问接口之前执行的，我们只需要在这里写验证登陆状态的业务逻辑，就可以在用户调用指定接口之前验证登陆状态了
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //log.debug("请求地址：{}", request.getRequestURL());
        // 管理端路径需校验权限，是否登录
        // 请求头获取token
        String token = request.getHeader("token");
        // 获取用户ID
        String userId = JwtUtils.getUserId(token);
        String redisKey = CommonsConstant.RedisPrefix.SSO_TOKEN + ":" + userId;
        // 验证Redis中该token是否存在
        boolean hasToken = this.redisUtils.hasKey(redisKey);

        if (hasToken) {
            // 刷新token时间
            this.redisUtils.expire(redisKey, this.sysProperties.getJwt().getTimeout());
            // 验证通过放行
            return true;
        } else {
            response.reset();
            response.setContentType("application/json; charset=utf-8");
            ServletOutputStream out = response.getOutputStream();

            R result = R.failure(HttpStatus.UNAUTHORIZED.value(), "未登录或登录超时，请重新登录");
            byte[] bytes = JSON.toJSONString(result).getBytes(StandardCharsets.UTF_8);
            out.write(bytes);

            return false;
        }
    }

}
